package com.framework.plugin.xmlsql.tag;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;

public class WhenTag extends DefaultTag {
	
	private ChooseTag chooseTag;
	
	public WhenTag(Map<String, Object> map) {
		super.setMap(map);
	}

	public ChooseTag getChooseTag() {
		return chooseTag;
	}

	public void setChooseTag(ChooseTag chooseTag) {
		this.chooseTag = chooseTag;
	}

	@Override
	public String createSql(String text) {
		List<Boolean> whens = chooseTag.getWhens();
		String sql = chooseTag.getSql();
		if(whens.get(whens.size()-1))
			sql += text;
		return sql;
	}

	@Override
	public void prepare() {
		String expression = attr("test");
		try {
			boolean value = (Boolean)Ognl.getValue(expression, getMap());
			List<Boolean> list = chooseTag.getWhens();
	    	if(list==null) {
	    		list = new ArrayList<Boolean>();
	    	}
	    	list.add(value);
	    	chooseTag.setWhens(list);
		} catch (OgnlException e) {
			e.printStackTrace();
		}
	}

}
